package com.technology.education.ui.common.modify_phone

import android.os.CountDownTimer
import androidx.lifecycle.MutableLiveData
import com.technology.education.ext.toast
import com.technology.education.network.apiService
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.callback.databind.BooleanObservableField
import me.hgj.jetpackmvvm.callback.databind.StringObservableField
import me.hgj.jetpackmvvm.ext.request

/**
 *@author:create by BZY
 *Date: 2022/5/18 10
 */
class ModifyPhoneViewModel : BaseViewModel() {
    val code = StringObservableField()
    val codeNotify = StringObservableField("发送验证码")
    val sendCodeEnable = BooleanObservableField(true)
    val account = StringObservableField()
    val result = MutableLiveData<Boolean>()

    fun sendCode() {
        if (account.get().isEmpty()) {
            toast("请输入新绑定的手机号")
            return
        }
        request({ apiService.sendCode(hashMapOf("mobile" to account.get())) }, success = {
            countDown()
        },error = {
            toast(it.errorMsg)
        }, isShowDialog = false)
    }


    fun checkCode() {
        if (account.get().isEmpty()) {
            toast("请输入新绑定的手机号")
            return
        }
        if (code.get().isEmpty()) {
            toast("请输入收到的验证码")
            return
        }
        if (code.get().length < 6) {
            toast("请输入正确的验证码")
            return
        }
        request({
            apiService.changeMobile(
                hashMapOf(
                    "authCode" to code.get(),
                    "mobile" to account.get()
                )
            )
        }, success = {
            result.postValue(true)
        }, error = {
            toast(it.errorMsg)
        })
    }

    private var timer: CountDownTimer? = null
    private fun countDown() {
        if (timer == null) {
            timer = object : CountDownTimer(60 * 1000, 1000) {
                override fun onTick(p0: Long) {
                    codeNotify.set("${p0 / 1000}s 后重试")
                    sendCodeEnable.set(false)
                }

                override fun onFinish() {
                    codeNotify.set("重新发送")
                    sendCodeEnable.set(true)
                }
            }
        }
        timer?.start()
    }
}